import React, { useImperativeHandle } from 'react'
import {
  Form, Input, Select, TreeSelect
} from 'antd'
import { useForm } from 'antd/es/form/Form'

function AForm(props, ref) {
  const {
    itemList = [], labelCol = { span: 6 }, wrapperCol = { span: 18 }, labelAlign = 'right',
    initialValues, children, ...params
  } = props

  /**
   *
   * @param {*} data 用于select等渲染的data
   *            placeholder
   *            dom 自定义渲染的dom
   * @returns
   */
  const renderContent = ({
    type, 
    render = {
      options: {},
      shouldUpdateKey: '',
      dom: ''
    }
  }) => {
    switch (type) {
      case 'custom':
        return render.dom
      case 'select':
        return <Select placeholder="请选择" {...render.options} />
      case 'treeSelect':
        return <TreeSelect placeholder="请选择" {...render.options} />
      default:
        return <Input placeholder="请输入" allowClear {...render.options} />
    }
  }
  const [form] = useForm()

  useImperativeHandle(ref, () => ({
    form,
    setFieldsValue: (value) => form.setFieldsValue(value),
    getFieldsValue: () => form.getFieldsValue(),
    onFinish: () => form.submit(),
    resetFields: () => form.resetFields()
  }))

  return (
    <Form
      form={form}
      labelAlign={labelAlign}
      labelCol={labelCol}
      labelWrap
      wrapperCol={wrapperCol}
      initialValues={initialValues}
      colon={false}
      requiredMark={false}
      {
        ...params
      }
    >
      {
        itemList.map((item) => {
          // 动态渲染字段
          if (item.shouldUpdate) {
            return (
              <Form.Item
                noStyle
                shouldUpdate={
                  (prevValues, currentValues) => prevValues[item.render.shouldUpdateKey] !== currentValues[item.render.shouldUpdateKey]
                }
                key={item.name}
              >
                {renderContent(item)}
              </Form.Item>
            )
          }
          // 默认
          return (
            <Form.Item label={item.label} name={item.name} rules={item.rules} key={item.name} {...item.formItemOptons}>
              {renderContent(item)}
            </Form.Item>
          )
        })
      }
      {children}
    </Form>
  )
}
export default React.forwardRef(AForm)
